package com.fh.rentcar.Controller;

import com.fh.rentcar.pojo.Cars;
import com.fh.rentcar.pojo.City;
import com.fh.rentcar.pojo.Shops;
import com.fh.rentcar.pojo.Street;
import com.fh.rentcar.service.CarsService;
import com.fh.rentcar.service.CityService;
import com.fh.rentcar.service.ShopService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cars")
public class CarController {
    @Autowired
    private CityService cityService;
    @Autowired
    private CarsService carsService;
    @Autowired
    private ShopService shopService;

    /**
     * 车型查询 (按城市显示车辆)
     * 分页默认按成都第一页
     */
    @RequestMapping("/pages/{pageNo}")
    public String shopByCar(@PathVariable("pageNo") int pageNo,Model mc){
        City city = cityService.getCityName("成都");
        PageHelper.startPage(pageNo,12);
        List<Cars> list = carsService.carByCity(city.getId());
        PageInfo<Cars> pages = new PageInfo<Cars>(list);
        mc.addAttribute("citys",city);
        mc.addAttribute("pages",pages);
        return "carlistByCity";
    }
    /**
     * 根据城市选出车辆(按城市显示车辆+分页)
     */
    @RequestMapping("/pages/{cname}/{pageNo}")
    public String optCarByCity(@PathVariable("cname") String cname,@PathVariable("pageNo") int pageNo,Model model){
        //获取城市id
        City city = cityService.getCityName(cname);
        //根据id获取车辆
        PageHelper.startPage(pageNo,12);
        List<Cars> list = carsService.carByCity(city.getId());
        PageInfo<Cars> pages = new PageInfo<Cars>(list);
        model.addAttribute("citys",city);
        model.addAttribute("pages",pages);
        String cn = cname+"/";
        model.addAttribute("cn",cn);
        return "carlistByCity";
    }

    /**
     * 根据车名和城市显示 门店
     */
    @RequestMapping("/carShops/{city}/{cname}")
    public String optCarByCarCityName(@PathVariable("city") String cityName,@PathVariable("cname") String carName,Model model){
        City city = cityService.getCityName(cityName);
        //map动态存储条件
        HashMap<String,Object> condition = new HashMap<String, Object>();
        condition.put("city_id",city.getId());
        condition.put("name",carName);

        List<Cars> carsList = carsService.findCarByCondition(condition);//多条件动态查询
        List<Street> streetList = cityService.getStreetId(city.getId());
        Cars cars = carsService.carByName(carName);

        model.addAttribute("streetList",streetList);
        model.addAttribute("carShopList",carsList);
        model.addAttribute("car",cars);
        model.addAttribute("citys",city);
        return "carInfo";
    }
    /**
     * 根据街道显示 门店
     */
    @RequestMapping("/carShops/{city}/{cname}/{street}")
    public String optCarByStreetName(@PathVariable("city") String cityName,@PathVariable("cname") String carName,@PathVariable("street") String street,Model model){
        City city2 = cityService.getCityName(cityName);
        //map动态存储条件
        HashMap<String,Object> condition = new HashMap<String, Object>();
        condition.put("cityId",city2.getId());
        condition.put("name",carName);
        condition.put("streetId",street);
        List<Cars> carsList = carsService.findCarByCondition(condition);
        List<Street> streetList = cityService.getStreetId(city2.getId());
        Cars cars = carsService.carByName(carName);

        model.addAttribute("streetList",streetList);
        model.addAttribute("carShopList",carsList);
        model.addAttribute("car",cars);
        model.addAttribute("citys",city2);
        return "carInfo";
    }
    /**
     * 查看门店车辆
     * 根据 sid
     */
    @RequestMapping("/shopsCar/{sid}")
    public String optCarListByShop(@PathVariable("sid") int sid,Model model){
        HashMap<String,Object> condition = new HashMap<String, Object>();
        condition.put("shop_id",sid);
        List<Cars> carsList = carsService.findCarByCondition(condition);
        Shops shop = shopService.getShopById(sid);
        model.addAttribute("shopCarList",carsList);
        model.addAttribute("shop",shop);
        return "shopCars";
    }


    /**
     * 车辆查询 车名 排量 租金 所属城市
     */
    @RequestMapping("/getCarByBlur")
    public String getCarByBlur(Model model,String sel_name,String sel_carml,String sel_rent){
        HashMap<String,Object> maps = new HashMap<String, Object>();
        if(sel_name!=null && !"".equals(sel_name)){
            maps.put("name",sel_name);
        }
        if(sel_carml!=null && !"".equals(sel_carml)){
            maps.put("carml",sel_carml);
        }
        if(sel_rent!=null && !"".equals(sel_rent)){
            maps.put("rentprice",sel_rent);
        }
        List<Cars> carsList=carsService.findCarByCondition(maps);
        if (carsList.isEmpty()){
            carsList=carsService.getAllCars();
        }
        model.addAttribute("cars",carsList);
        return "/admin/carManage";
    }


    /**
     *
     * 车辆上传
     */
    @RequestMapping("/uploadCarImg")
    @ResponseBody
    public Map<String, Object> uploadFile(HttpServletRequest servletRequest, @RequestParam("file") MultipartFile file)
            throws IOException {
        // 如果文件内容不为空，则写入上传路径
        if (!file.isEmpty()) {
            // 上传文件路径 相对路径

            String s = System.getProperty("user.dir");
            String UploadPath = s+"\\src\\main\\webapp\\statics\\images";
            //取得原文件名字
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            //取得文件后缀
//            String suffix = fileName.substring(fileName.lastIndexOf("."));
            //提取系统时间作为新文件名
//            String prefix = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date().getTime());
            //保存路径
            // 上传文件名
//            String filename = prefix+suffix;
            File filepath = new File(UploadPath, fileName);
            // 判断路径是否存在,没有创建
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            // 将上传文件保存到一个目标文档中
            File file1 = new File(UploadPath + File.separator + fileName);
            file.transferTo(file1);
            Map<String, Object> res = new HashMap<>();
            // 返回的是一个url对象,图片名称
            res.put("name", fileName);
            res.put("url","/image/"+filepath);
            return res;
        } else {
            return null;
        }
    }

    //增加车辆
    @RequestMapping("/addCar")
    @ResponseBody
    public String addCar(Cars cars){
        System.out.println("车辆信息"+cars);
        carsService.addCar(cars);
        return "ok";
    }

    /**
     * 多条件查询车辆
     */
    @RequestMapping("/getCarByMoreConditions")
    @ResponseBody
    public List<Cars> getCarMoreConditions(String name,String carml,String rentprice,String cityName){
//        findCarByCondition

        HashMap<String,Object> maps = new HashMap<>();
        if(name!=null && !name.equals("")){
            maps.put("name",name);
        }
        if(carml!=null && !carml.equals("")){
            maps.put("carml",carml);
        }
        if(rentprice!=null && !rentprice.equals("")){
            maps.put("rentprice",rentprice);
        }
        if(!cityName.equals("")){
            City city = cityService.getCityName(cityName);
            if(city!=null){
                maps.put("city_id",city.getId());
            }
        }

        List<Cars> cs = carsService.findCarByCondition(maps);
        return cs;
    }

    @RequestMapping("/getCarListByName/{name}")
    @ResponseBody
    public List<Cars> getCarListByName(@PathVariable("name") String name){
        HashMap<String, Object> maps = new HashMap<>();
        maps.put("name",name);
        return carsService.findCarByCondition(maps);
    }

}
